<script setup>
import { use } from 'echarts/core'
import { LineChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, GridComponent, LegendComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import { ref, watch } from 'vue'

use([LineChart, TitleComponent, TooltipComponent, GridComponent, LegendComponent])

const props = defineProps({
  data: {
    type: Object,
    required: true
  },
  title: {
    type: String,
    default: ''
  },
  height: {
    type: String,
    default: '400px'
  }
})

const option = ref({
  title: {
    text: props.title,
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['价格'],
    left: 'right'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: props.data.dates
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: '{value} 元'
    }
  },
  series: [
    {
      name: '价格',
      type: 'line',
      data: props.data.prices,
      smooth: true,
      markPoint: {
        data: [
          { type: 'max', name: '最大值' },
          { type: 'min', name: '最小值' }
        ]
      },
      markLine: {
        data: [{ type: 'average', name: '平均值' }]
      }
    }
  ]
})

watch(() => props.data, (newVal) => {
  option.value.xAxis.data = newVal.dates
  option.value.series[0].data = newVal.prices
}, { deep: true })

watch(() => props.title, (newVal) => {
  option.value.title.text = newVal
})
</script>

<template>
  <v-chart class="chart" :option="option" :style="{ height }" />
</template>

<style scoped>
.chart {
  width: 100%;
}
</style>